package com.sunrise.xdoc.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.sunrise.xdoc.dao.IBaseDao;
import com.sunrise.xdoc.entity.operator.Function;
import com.sunrise.xdoc.entity.operator.Module;
import com.sunrise.xdoc.entity.operator.OperatorProfile;
import com.sunrise.xdoc.entity.operator.Privilege;
import com.sunrise.xdoc.service.AbstractService;
import com.sunrise.xdoc.service.IOperatorService;

@Service("operatorService")
public class OperatorService extends AbstractService implements IOperatorService {
	private static final long serialVersionUID = 7876399532414659211L;

	@Override
	public Map<Module, List<Function>> getMapModule2Functions() {
		IBaseDao<Function> functionDao = getDaoHelper().getDao(Function.class);
		DetachedCriteria dc = functionDao.getDetachedCriteria();
		dc.add(Restrictions.eq("active", true));
		dc.createCriteria("module", "m").add(Restrictions.eq("m.active", true));
		List<Function> functions = functionDao.findByCriteria(dc);
		Map<Module, List<Function>> m2f = new HashMap<>();
		for (Function f : functions) {
			List<Function> fs = m2f.get(f.getModule());
			if (fs == null) {
				fs = new ArrayList<>();
				m2f.put(f.getModule(), fs);
			}
			fs.add(f);
		}
		return m2f;
	}

	@Override
	public List<Privilege> getPrivilegeByOperatorProfileId(Long operatorProfileId) {
		IBaseDao<Privilege> privilegeDao = getDaoHelper().getDao(Privilege.class);
		DetachedCriteria dc = privilegeDao.getDetachedCriteria();
		dc.createCriteria("profile", "op").add(Restrictions.eq("op.id", operatorProfileId));
		return privilegeDao.findByCriteria(dc);
	}

	@Override
	public OperatorProfile getOperatorProfile(Long operatorProfileId) {
		return getDaoHelper().getDao(OperatorProfile.class).findById(operatorProfileId);
	}

	@Override
	public void saveOrUpdatePrivileges(List<Privilege> privileges) {
		for (Privilege privilege : privileges) {
			if (privilege.getPossibleMode().isEmpty()) {
				getDaoHelper().getDao(Privilege.class).delete(privilege);
			} else {
				getDaoHelper().getDao(Privilege.class).saveOrUpdate(privilege);
			}
		}
	}

	@Override
	public void deletePrivileges(List<Privilege> privileges) {
		getDaoHelper().getDao(Privilege.class).deleteAll(privileges);
	}
}
